<!--
 * @Author: 黄威
 * @Date: 2021-11-23 16:51:11
 * @LastEditors: 黄威
 * @LastEditTime: 2022-03-02 10:38:08
 * @Description: 资源目录树
-->

<template>
    <mgs-service-catalog
        ref="catalog"
        v-loading="loading"
        :bind-map="bindMap"
        :get-icon="getIcon"
        :data="treeData"
        @service-add="$emit('service-add', $event)"
        @service-remove="$emit('service-remove', $event)"
    />
</template>

<script>
import MgsServiceCatalog from '@mgs/components/mgs-service-catalog';
import { transformToTreeData } from '@mgs/utils/tree';
import MapAPI from '@/apis/mapApi';

export default {
    components: { MgsServiceCatalog },
    props: {
        bindMap: Object,
        // 默认加载的图层（可用于 对比服务 加载默认服务）
        loadDefaultService: { type: Boolean, default: false },
    },
    data() {
        return {
            // 加载状态
            loading: true,
            // arr
            treeData: null,

            // icon获取
            getIcon(nodetype) {
                const imgMapper = { l: 'layer', s: 'service' };
                return `./img/serviceCatalog/${
                    imgMapper[nodetype] || 'folder'
                }.png`;
            },
        };
    },
    created() {
        MapAPI.getServiceTree()
            .then(res => {
                this.treeData = transformToTreeData(res, {
                    idKey: 'pkid',
                    parentKey: 'parentid',
                    labelKey: 'catalogalias',
                });

                // 加载默认服（前三个服务）
                if (this.loadDefaultService) {
                    this.$nextTick(() => {
                        const ids = [];

                        for (let i = 0; i < res.length; i++) {
                            const { servicetype, uid } = res[i];
                            if (
                                servicetype >= 1 &&
                                servicetype <= 4 &&
                                ids.length < 3
                            ) {
                                ids.push(uid);
                            }
                        }

                        this.$refs.catalog.resTree.setCheckedKeys(ids);
                    });
                }
            })
            .finally(() => (this.loading = false));
    },
};
</script>
